<script lang="ts">
import { onMount } from "svelte";
import { parseScheduleHtml } from "$lib/Data/hololive";
import { typeSchedule } from "$lib/Hololive/hololive";
import Lives from "$lib/Hololive/Lives.svelte";
import HeadTitle from "$lib/Home/HeadTitle.svelte";
import Message from "$lib/Loading/Message.svelte";
import Skeleton from "$lib/Loading/Skeleton.svelte";
import proxy from "$lib/Utility/proxy";
import root from "$lib/Utility/root";
import identity from "$stores/identity";
import locale from "$stores/locale";
import type { PageData } from "./$types";

export let data: PageData;

let schedulePromise: Promise<Response>;
let pinnedStreams: string[] = [];

onMount(() => getPinnedStreams());

const getPinnedStreams = () => {
	let streams: string[] = [];

	const setSchedule = () => {
		pinnedStreams = streams;
		schedulePromise = fetch(proxy("https://schedule.hololive.tv"), {
			headers: {
				Cookie: "timezone=Asia/Tokyo",
			},
		});
	};

	if ($identity.id !== -2) {
		fetch(root(`/api/preferences?id=${$identity.id}`)).then((response) => {
			if (response.ok)
				response.json().then((data) => {
					if (data?.pinned_hololive_streams)
						streams = data.pinned_hololive_streams;

					setSchedule();
				});
		});

		return;
	}

	setSchedule();
};
</script>

<HeadTitle routeKey="hololiveSchedule" path="/hololive" />

{#await schedulePromise}
  <Message message={$locale().hololive.loadingSchedule} />

  <Skeleton grid={true} count={100} width="49%" height="16.25em" />
{:then scheduleResponse}
  {#if scheduleResponse}
    {#await scheduleResponse.text()}
      <Message message={$locale().hololive.parsingSchedule} />

      <Skeleton grid={true} count={100} width="49%" height="16.25em" />
    {:then untypedSchedule}
      {@const schedule = typeSchedule(parseScheduleHtml(untypedSchedule))}

      <Lives {schedule} {pinnedStreams} {getPinnedStreams} filter={data.stream} />
    {:catch}
      <Message loader="ripple" slot>
        {$locale().hololive.parseError}
        <a href={'#'} onclick={() => location.reload()}>{$locale().hololive.tryAgainQuestion}</a>
      </Message>
    {/await}
  {:else}
    <Message message={$locale().hololive.loadingSchedule} />

    <Skeleton grid={true} count={100} width="49%" height="16.25em" />
  {/if}
{:catch}
  <Message loader="ripple" slot>
    {$locale().hololive.loadError} {$locale().hololive.pleasePrefix}
    <a href={'#'} onclick={() => location.reload()}>{$locale().common?.tryAgain}</a> {$locale().hololive.laterSuffix}
  </Message>
{/await}
